package cn.edu.bupt.scidata.controller;

import cn.edu.bupt.scidata.mapper.RelationMapper;
import cn.edu.bupt.scidata.model.team.Relation;
import cn.edu.bupt.scidata.model.team.RelationVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/team/api")
public class RestController {
    @Resource
    RelationMapper relationMapper;

    @RequestMapping("/relation")
    @ResponseBody
    public RelationVo getRelation(@RequestParam(name = "team_id") Integer team_id){
        List<Relation> relations = relationMapper.selectByTeamId(team_id);
        relations.sort(Comparator.comparingInt(Relation::getpId));
        RelationVo res = null;
        Map<Integer, RelationVo> map = new HashMap<>();
        for(Relation r : relations){
            int id = r.getId();
            int pid = r.getpId();
            if(map.get(id) == null){
                RelationVo ele = new RelationVo(r.getName(), new ArrayList<RelationVo>());
                if(pid != -1){
                    map.get(pid).getChildren()
                            .add(ele);
                    map.put(id, ele);
                }else{
                    map.put(id, ele);
                    res = ele;
                }
            }

        }
        return res;
    }
}
